package com.cskaoyan.filter;

import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.servlet.AdminAuthServlet;
import com.cskaoyan.util.JsonUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@WebFilter("/*")
public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 访问Servlet之前做什么？
        crossOrigin(servletResponse);
        boolean flag = releaseStorageFetch(servletRequest);
        if (flag) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        // 1. 字符集处理
        processCharacter(servletRequest, servletResponse);
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // 2. 跨域请求处理 crossOrigin
        if (isLogin(request) || hasLogin(request)) {
            // 放行
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            // 不放行 做什么 → 告知别人请先登录
            BaseRespVo baseRespVo = BaseRespVo.msg("请先登录");
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            Cookie cookie = new Cookie("X-Cskaoyanmarket-Admin-Token", "");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            String jsonStr = JsonUtil.write(baseRespVo);
            servletResponse.getWriter().println(jsonStr);
        }

        // 访问Servlet之后做什么
    }

    private boolean releaseStorageFetch(ServletRequest servletRequest) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        boolean flag = uri.startsWith("/wx/storage/fetch");
        return flag;
    }

    // 跨域处理
    private void crossOrigin(ServletResponse servletResponse) {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type,X-CskaoyanMarket-Admin-Token,X-CskaoyanMarket-Token");
        response.setHeader("Access-Control-Allow-Credentials","true");
    }

    /**
     * session中是否有用户信息
     * @param request
     * @return
     */
    private boolean hasLogin(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Integer adminId = (Integer) session.getAttribute(AdminAuthServlet.USER_KEY);

        return adminId != null;
    }

    /**
     * 判断是否是登录请求 /admin/auth/login
     * @param request
     * @return
     */
    private boolean isLogin(HttpServletRequest request) {
        String uri = request.getRequestURI();
        return uri.endsWith("/admin/auth/login");
    }

    private void processCharacter(ServletRequest servletRequest, ServletResponse servletResponse) throws UnsupportedEncodingException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("application/json;charset=utf-8");
    }

    @Override
    public void destroy() {

    }
}
